const db = require('../db/index.js')

function addUser(ctx) {
  return new Promise(resolve => {
    let msg = ''
    const { name } = ctx.request.body
    db.user.find({ name }, function(err, docs) {
      if (!err && docs.length === 0) {
        db.user.insert({
          ...ctx.request.body,
          created: Date.now()
        })
        ctx.response.status = 200
        msg = '添加成功'
      } else {
        ctx.response.status = 400
        msg = err || '已经存在'
      }
      ctx.response.body = {
        msg
      }
      resolve()
    })
  })
}

function getUserList(ctx) {
  return new Promise(resolve => {
    db.user.find({}, function(err, data) {
      if (err) {
        ctx.response.status = 400
        ctx.response.body = err
        return
      }
      ctx.response.status = 200
      ctx.response.body = data
      resolve()
    })
  })
}

module.exports = {
  addUser,
  getUserList
}
